<template>
  <a-card title="图书列表" style="width: 80%; margin:20px auto; ">
    <template #extra>
      <a-button type="primary" @click="this.$router.push('/book/bookadd')">添加</a-button>
    </template>
    <a-table :columns="columns" :data-source="dataSource">
      <template #bodyCell="{ column, text, record }">
        <template v-if="['name', 'price','category','publish_time'].includes(column.dataIndex)">
          <div>
            <a-input
              v-if="editableData[record.id]&&column.dataIndex=='name'"
              v-model:value="editableData[record.id][column.dataIndex]"
            />
            <a-input-number v-else-if="editableData[record.id]&&column.dataIndex=='price'"
                            :min="0" :max="10000" :step="0.01" string-mode
                            v-model:value="editableData[record.id][column.dataIndex]"
                            />
            <a-select v-else-if="editableData[record.id]&&column.dataIndex=='category'"
                      v-model:value="editableData[record.id][column.dataIndex]" style="width: 100%;">
              <a-select-option value="PHP">PHP</a-select-option>
              <a-select-option value="Java">Java</a-select-option>
              <a-select-option value="Python">Python</a-select-option>
              <a-select-option value="C++">C++</a-select-option>
              <a-select-option value="其他">其他</a-select-option>
            </a-select>
            <a-date-picker v-else-if="editableData[record.id]&&column.dataIndex=='publish_time'"
              style="width: 100%;" v-model:value="editableData[record.id][column.dataIndex]"
                           value-format="YYYY-MM-DD"/>
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
          <span v-if="editableData[record.id]">
            <a-typography-link @click="save(record.id)">保存</a-typography-link>
            <a-popconfirm title="确定取消?" @confirm="cancel(record.id)">
              <a>取消</a>
            </a-popconfirm>
          </span>
            <span v-else>
              <a-button @click="edit(record.id)" style="margin-right: 10px"
                        type="primary">编辑</a-button>
              <a-popconfirm title="确认删除？" ok-text="是" cancel-text="否"
                            @confirm="del(record.id)">
               <a-button type="primary" danger>删除</a-button>
              </a-popconfirm>
          </span>

          </div>
        </template>
      </template>
    </a-table>
  </a-card>

</template>
<script lang="ts" setup>
import {cloneDeep} from 'lodash-es';
import {onMounted, reactive, ref} from 'vue';
import type {UnwrapRef} from 'vue';
import axios from 'axios';
import {message} from "ant-design-vue";

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: '5%',
  },
  {
    title: '图书名称',
    dataIndex: 'name',
    width: '22%',
  },
  {
    title: '分类',
    dataIndex: 'category',
    width: '16%',
  },
  {
    title: '价格',
    dataIndex: 'price',
    width: '16%',

  }, {
    title: '出版日期',
    dataIndex: 'publish_time',
    width: '16%',

  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '25%',
  },
];

interface DataItem {
  id: string;
  name: string;
  category: string;
  price: number;
  publish_time: string;
}

const data: DataItem[] = [];
for (let i = 0; i < 10; i++) {
  data.push({
    id: 1 + i + '',
    name: 'PHP从入门到精通',
    category: 'PHP',
    price: 50.00,
    publish_time: '2019-02-17',
  });
}
// const dataSource = ref(data);
const dataSource = ref([]);
const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});

const edit = (id: string) => {
  editableData[id] = cloneDeep(dataSource.value.filter(item => id === item.id)[0]);
};
const del = (id: string) => {
  axios({
    method: 'post',
    url: 'https://139.159.233.82/api/book/removeById',
    data: {id},
    headers: {'Content-Type': 'application/json'},
    timeout: 2000, // 设置超时时间（单位：毫秒）
  })
    .then(response => {
      if (response.data.code === 20000) {
        dataSource.value = dataSource.value.filter(item => id !== item.id)
        message.success('删除成功!');
      }
      console.log(response);
    })
    .catch(error => {
      console.error(error);
    });
};
const save = (id: string) => {
  Object.assign(dataSource.value.filter(item => id === item.id)[0], editableData[id]);

  axios({
    method: 'post',
    url: 'https://139.159.233.82/api/book/updateById',
    data: {
      id: id,
      name: dataSource.value.filter(item => id === item.id)[0].name,
      category: dataSource.value.filter(item => id === item.id)[0].category,
      price: dataSource.value.filter(item => id === item.id)[0].price,
      publish_time: dataSource.value.filter(item => id === item.id)[0].publish_time,
    },
    headers: {'Content-Type': 'application/json'},
    timeout: 2000, // 设置超时时间（单位：毫秒）
  })
    .then(response => {
      if (response.data.code === 20000) {
        console.log(response);
        message.success('修改成功!');
      }
    })
    .catch(error => {
      console.error(error);
    });


  delete editableData[id];

};
const cancel = (id: string) => {
  delete editableData[id];
};
const listTeam = () => {
  axios({
    method: 'post',
    url: 'https://139.159.233.82/api/book/queryAll',
    headers: {'Content-Type': 'application/json'},
    timeout: 2000, // 设置超时时间（单位：毫秒）
  })
    .then(response => {
      dataSource.value = response.data.data;
      console.log(response.data.data);
      console.log(dataSource.value);
    })
    .catch(error => {
      console.error(error);
    });
}
// 页面加载时只触发一次
onMounted(() => {
  listTeam();
})
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
